﻿using AiXiu.BLL;
using AiXiu.Common;
using AiXiu.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AiXiu.WebSite
{
    public partial class AvatarEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //读取用户信息
                TBUsers user = IdentityManager.ReadUser();
                if (string.IsNullOrEmpty(user.Avatar))
                {
                    avatar.ImageUrl = "~/imgs/avatar.jpg";
                }
                else
                {
                    avatar.ImageUrl = user.Avatar;
                }
                btnSave.Visible = false;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            // 读取信息
            TBUsers user = IdentityManager.ReadUser();
            user.Avatar = this.avatar.ImageUrl;
            // 更新资料
            UsersBLL userManager = new UsersBLL();
            OperResult<TBUsers> editResult = userManager.EditAvatar(user);
            if (editResult.StatusCode == StatusCode.Succeed)
            {
                // 读取缓存用户资料
                TBUsers userCookie = IdentityManager.ReadUser();
                if (userCookie == null)
                {
                    this.Alert("cookienull", "缓存读取出错！");
                }
                userCookie.Avatar = user.Avatar;
                // 更新缓存用户资料
                IdentityManager.SaveUser(userCookie);
                // 跳转到个人页
                Response.Redirect("Personal.aspx");
            }
            else
            {
                this.Alert("editerror", editResult.Message);
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile) //判断是否上传了文件
            {
                string savePath = Server.MapPath("~/Avatar/");//指定上传文件在服务器上的保存路径
                //检查服务器上是否存在这个物理路径，如果不存在，则创建
                if (!System.IO.Directory.Exists(savePath))
                {
                    //对该路径应该有足够的权限，否则报错
                    System.IO.Directory.CreateDirectory(savePath);
                }

                savePath = savePath + FileUpload1.FileName;
                FileUpload1.SaveAs(savePath); //保存文件

                avatar.ImageUrl = "/Avatar/" + FileUpload1.FileName;
                btnSave.Visible = true;
            }
            else
            {
                this.Alert("e", "请选择图片！");
            }
        }
    }
}